// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {
  Array.prototype.forEach = function (callback, thisArg) {
    var T, k;
    if (this == null) {
      throw new TypeError(' this is null or not defined');
    }

    // 1. Let O be the result of calling toObject() passing the
    // |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get() internal
    // method of O with the argument "length".
    // 3. Let len be toUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If isCallable(callback) is false, throw a TypeError exception. 
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== "function") {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let
    // T be undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6. Let k be 0
    k = 0;

    // 7. Repeat, while k < len
    while (k < len) {

      var kValue;

      // a. Let Pk be ToString(k).
      //    This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty
      //    internal method of O with argument Pk.
      //    This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal
        // method of O with argument Pk.
        kValue = O[k];

        // ii. Call the Call internal method of callback with T as
        // the this value and argument list containing kValue, k, and O.
        callback.call(T, kValue, k, O);
      }
      // d. Increase k by 1.
      k++;
    }
    // 8. return undefined
  };
}
;(function (window, undefined) {
  /*
  ┏━━━━━━━━━┓
  ┃ 通用漫画阅读页类 ┃
  ┗━━━━━━━━━┛
  ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
  ┃ 必需json对象mh_info和jQuery框架                    ┃
  ┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛

  子域名
  server      用于获取线路
  mhpic     未获取到线路时默认线路

  css类名 
  mh_headpager  顶部页码
  mh_footpager  底部页码
  mh_prevbook   上一章
  mh_nextbook   下一章
  mh_prevpage   上一页
  mh_nextpage   下一页
  mh_select   下拉选择
  mh_loading    正在加载
  mh_readmode   切换阅读模式
  mh_comiclist  装载全部图片的容器
  mh_comicpic   装载单页图片的容器

  cookie名
  mh_thispage   当前页码
  mh_linelist   线路列表
  mh_thisline   当前线路
  mh_readmode   阅读模式
  urecord     阅读记录

  功能说明

  01、阅读模式支持切换：单击、双击、连续模式
  02、支持一次预加载多张图片，数量在json对象中配置
  03、图片下载出错或超时能自动切换线路，并且可手动重载图片
  04、支持用户通过测试网速选择最快的线路
  05、支持常用翻页热键，支持鼠标右键点击图片时翻到上一页（非连续模式下）
  06、能同时支持鼠标左右键拖拽图片
  07、支持+-0键缩放图片（兼容小键盘）
  08、页面内容区域为浏览器宽度的75%，最小宽度或IE6下为960px
  09、反馈及测速功能采用按需加载的方式，减少默认代码加载量
  10、章节末尾显示提示页，体验更好，且能增加1个PV
  11、连续模式支持插入图间广告
  12、章节阅读页码记录整合到漫画阅读记录，避免cookie过大
  13、连续模式使用定时器加载图片，并限制同一时间只能加载一张图片
  14、当前浏览的图片如果还未预加载完，将取消其预加载线程，避免同时2个线程加载1张图片，浪费带宽
  15、重载图片时将之前未加载完的图片线程取消，避免同时2个线程加载1张图片，浪费带宽
  16、线路列表未请求到时将默认用域名调用图片，不会卡住页面
  17、已预加载的图片，切换线路后，该图片还是继续用之前预加载的URL
  18、图片路径加密防采集

  解码路径：
  mh_info.imgpath = mh_info.imgpath.replace(/./g,function(a){return String.fromCharCode(a.charCodeAt(0)-mh_info.pageid%10)});

  */
  /************** 用src方式输出代码 **************/
  /*window.__cr_count = window.__cr_count || 0;
  var this_src = $("script[src*='__cr.js']")[window.__cr_count].src.split("#");
  window.__cr_count++;

  if(this_src[1]) {
    //alert(this_src[1])
    switch(this_src[1]){
      case "headpager" :
        document.write('<div class="mh_headpager"><span class="mh_prevpage">上一页</span><select class="zssel mh_select"></select><span class="mh_nextpage">下一页</span></div>');
        break;
      case "footpager" :
        document.write('<div class="mh_footpager"><span class="mh_prevpage">上一页</span><select class="zssel mh_select"></select><span class="mh_nextpage">下一页</span></div><script>__cr.showPic()<\/script>');
        break;
      case "comiclist" :
        document.write('<div class="mh_comiclist"></div>');
        break;
      default:
        document.writeln(this_src[1]);
    }
    return;
  }
*/
  // 全局变量
  window.use_domain = {};
  window.lines = {};
  window.chapter_id = 0; //全局变量

  /************** 开始定义函数 **************/
  var __cr = window.__cr = {
    timeout: 10000
  }; //timeout是图片加载超时时间

  // 从cookie获得页码
  __cr.getPage = function () {
    var temp = __cr.cookie("urecord"),
      page = 1;
    if (!temp) return page;
    var tempArr = [];
    try {
      tempArr = eval(temp);
    } catch (e) {
      __cr.cookie("urecord", null);
    }
    $.each(tempArr, function (i, v) {
      //找到该漫画的该章节，且第5个元素页码字段不为空
      if (v[0] == mh_info.mhid && v[2] == mh_info.pageurl && v[5]) {
        page = parseInt(v[5]);
        return false; //跳出循环
      }
    });
    temp = null;
    return page;
  };
  // 设置阅读记录
  __cr.setRecord = function () {
    // [漫画ID,漫画名,章节url,章节名,阅读时间,章节页码]
    var p = __cr.thispage;
    
    //连续模式看到最后一页时将页码置为0表示已看完本章节
    if (p == mh_info.totalimg && __cr.userReadMode == 3) p = 0;


    var str = "[['" + mh_info.mhid + "','" + mh_info.mhname + "','" + mh_info.pageurl + "','" + mh_info.pagename + "','" + new Date().getTime() + "','" + p + "']";
    var temp = __cr.cookie("urecord") || [];
    $.each(eval(temp), function (i, v) {
      if (i >= 10) return false; // 总记录数不超过10条
      if (v[0] != mh_info.mhid) {
        str += ",['" + v.join("','") + "']";
      }
    });
    str += "]";
    // 页码大于1时才阅读记录
    __cr.cookie("urecord", str, {
      expires: 8760
    }); // 失效时间一年
    str = p = null;
  };
  // 跳转页码
  __cr.goPage = function (p) {
    $(window).scrollTop(0); //回顶部
    if (p == "next") p = __cr.thispage + 1;
    if (p == "prev") p = __cr.thispage - 1;
    p = parseInt(p, 10); //将字符串转数字，否则后面要出错
    if (p < 1) {
      alert("已经是第一页了");
      return false
    }
    __cr.thispage = p;
    __cr.setRecord();
    location = location.pathname + location.search;
    return false;
  };
  // 重载图片，但不刷新页面
  __cr.reloadPic = function (e, p) {
    window.stop ? window.stop() : document.execCommand("Stop"); //阻止未下完的图片
    $(e).parent().siblings("img").attr("src", __cr.getPicUrl(p));
    $(e).parent().hide(); //隐藏错误提示
    __cr.st_showerr[p] = setTimeout("__cr.imgOnError(" + p + ")", __cr.timeout); //重新开始计时
    return false;
  };
  __cr.cr = "w1355i56n63d6464o7267w8786.65p786r8579o95m98p00t31=78_32_53c54r54.54c54h34a55r78c89o98d97e97";
  // 网速测试，自动选择最快线路
  __cr.speedTest = function (e, p) {
    if (!$(".mod-speedtest").length) {
      $.ajax({
        url: "//feedback.yyhao.com/static/speedtest.js",
        dataType: "script",
        scriptCharset: "utf-8"
      });
      setTimeout(function () {
        __cr.speedTest(e, p)
      }, 1000);
    } else __st.init(e, "/comic/" + mh_info.imgpath + (p + mh_info.startimg - 1) + ".jpg" + (mh_info.comic_size || '') + "?" + new Date().getTime());
  };
  //获得线路列表，保存当前使用的线路，并检查该线路是否失效
  /*__cr.saveLine = function(linedata){
    var ld=eval(linedata),line = __cr.cookie("mh_thisline");
    if(!line || linedata.indexOf(line)==-1) __cr.cookie("mh_thisline",mh_info.defaultminline?ld[0][0]:"mhpic."+mh_info.domain,{expires:0.1});//当前线路保存6分钟，如果mh_info.defaultminline为真，则默认使用负载最小的线路，否则默认使用mhpic线路
    if(!__cr.cookie("mh_linelist")) __cr.cookie("mh_linelist",linedata,{expires:0.2});//线路列表保存12分钟
    __cr.linelist = ld;
    __cr.thisline = __cr.cookie("mh_thisline");
    ld = null;
  };*/
  // 保存线路到缓存
  __cr.setLine = function (json) {
    /*json = eval(json);
    if(!json||json.length==0) {
      return;
    }
    var arr = [];
    $.each(json, function(i, v){
      var obj = {
        domain: v[0],
        name:v[1],
        status:v[2]
      }
      arr.push(obj);
    });
    var cachelines = {
      "use_line":arr[0].domain,
      "all_line":arr,
      "expire": new Date().getTime() + 600000
    };*/
    if (!json || json.status > 0) {
      return;
    }

    var cachelines = {
      "use_line": json.data[0].domain,
      "all_line": json.data,
      "expire": 6e5 + new Date().getTime()
    };
    //保存lines[章节id]数据到缓存（以use_domain[章节id]为键）
    __cr.cookie(json.domain, JSON.stringify(cachelines)); // web上直接用cookie方法
    __cr.getLine(); //重新获得线路
  };
  __cr.saveLine = function (json) {
    json = eval(json);
    if (!json || json.length == 0) {
      return;
    }
    var arr = [];
    $.each(json, function (i, v) {
      var obj = {
        domain: v[0],
        name: v[1],
        status: v[2]
      };
      arr.push(obj);
    });
    var cachelines = {
      "use_line": arr[0].domain,
      "all_line": arr,
      "expire": 6e5 + new Date().getTime()
    };
    //保存lines[章节id]数据到缓存（以use_domain[章节id]为键）
    __cr.cookie(json.domain, JSON.stringify(cachelines), {
      expires: 1
    }); // web上直接用cookie方法
    __cr.getLine(); //重新获得线路
  };
  // 获得图片地址，参数p是页码，整型
  /*__cr.getPicUrl = function(p) {
    var thisline = window.thisline = __cr.thisline || "mhpic."+mh_info.domain;//使用线路
    if(thisline.indexOf("mhpic")==-1) thisline += ":82";//用IP访问时才带端口，防止移动DNS污染
    var filename = p+mh_info.startimg-1+".jpg"+(mh_info.comic_size||'');//图片文件名
    return "http://"+thisline+"/comic/"+mh_info.imgpath+filename;
  };*/
  // 获得指定页码的图片路径
  __cr.getPicUrl = function (page) {
    var fixed_line = lines[chapter_id].use_line;
    // if (fixed_line.indexOf("mhpic") == -1) {
    //   fixed_line += ":82"; //非mhpic域名需要走82端口
    // }
    var filename = (parseInt(mh_info.startimg) + page - 1) + ".jpg";
    var chapter_addr_rule = "https://" + fixed_line + '/comic/' + mh_info.imgpath + filename;
    return __cr.switchWebp(chapter_addr_rule, mh_info.comic_size); //web
  };
  // 从缓存获取线路
  __cr.getLine = function () {
    lines[chapter_id] = __cr.cookie(use_domain[chapter_id]); //web可以直接用cookie

    if (lines[chapter_id]) {
      lines[chapter_id] = JSON.parse(lines[chapter_id]); //将字符串转为Json对象
    } else {
      lines[chapter_id] = {
        "use_line": "mhpic." + use_domain[chapter_id],
        "all_line": [],
        "expire": 0
      }
    }
  };

  // 按页码p显示对应的漫画图片
  __cr.showPic = function (p) {
    p = p || __cr.thispage || 1; //阅读到最后一页，页码为0时的情况
    var mh_comiclist = $(".mh_comiclist");

    if (p > mh_info.totalimg) { //显示章节最后提示内容
      __cr.thispage = 0;
      __cr.setRecord(); //将页码归0表示已看完本章节
      $(function () {
        $(".mh_readend").show()
      }); //showPic执行时mh_readend的html代码还未加载到
    } else {
      var _totalimg = __cr.userReadMode == 3 ? mh_info.totalimg : p; //连续模式将所有img提前输出
      var _imgstr = '';

      new Function((function (p, a, c, k, e, d) {
        e = function (c) {
          return (c < a ? "" : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36))
        };
        if (!''.replace(/^/, String)) {
          while (c--) d[e(c)] = k[c] || e(c);
          k = [function (e) {
            return d[e]
          }];
          e = function () {
            return '\\w+'
          };
          c = 1;
        };
        while (c--)
          if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]);
        return p;
      }('4["\\1\\6\\0\\5\\1\\9"](8["\\3\\2\\7\\0\\3\\2"])', 10, 10, 'x6f|x70|x65|x64|window|x6d|x72|x63|__cr|x74'.split('|'), 0, {})))();

      var limitPage = 3
      // 付费只能看1页，免费看3页
      if (mh_info.price > 0) {
        limitPage = 1
      }
      for (var i = p; i <= _totalimg; i++) {
        if (__cr.isLimit() && (i > limitPage || p > limitPage)) {
          _imgstr += __cr.scheme.init()
          break;
        } else {
          _imgstr += '<div class="mh_comicpic" p="' + i + '"><img ' + (i == p ? 'src="' + __cr.getPicUrl(p) + '"' : 'd') + '/>';
          _imgstr += __cr.isLimit() ? '<span class="try-read"><img src="//image.mhxk.com/file/global/' + __cr.scheme.getHost() + '_tryread.png" /></span>' : ''
          if (__cr.userReadMode != 3) {
            _imgstr += '<br>第 ' + i + ' 页 / 共 ' + mh_info.totalimg + ' 页<br>';
          }
          _imgstr += '<div class="mh_loading">服务器君正在努力载入图片，请稍候...</div><div class="mh_loaderr">已长时间未能载入图片，您可以：<br><span onclick="__cr.reloadPic(this,' + i + ')" class="mh_btn">重载图片</span> <span class="mh_btn contact">反馈报错</span> <span onclick="__cr.speedTest(this,' + i + ')" class="mh_btn">网速测试</span></div></div>';
        }
      }

      document.writeln(_imgstr);
      _totalimg = _imgstr = null;
      $(".mh_loaderr").hide(); //隐藏所有错误提示
      $(".mh_loading:gt(0)").hide(); //只保留第一张图的加载提示，其他都隐藏

      __cr.st_showerr = []; //下载超时10秒以后显示错误
      __cr.st_showerr[p] = setTimeout("__cr.imgOnError(" + p + ")", __cr.timeout);

      if (__cr.userReadMode == 3) {
        $(function () {
          $(".mh_readend").show()
        }); //连续模式将章节最后提示显在最后
        __cr.isloading = true; //防止第1张图未加载完时第2张图开始加载，导致第1张图不显
        __cr.si_lazyload = setInterval(__cr.lazyLoad, 200);
      } else {
        clearInterval(__cr.si_lazyload);
      }

      __cr.bindEvent(); //事件处理
    }
  };


  // 图片加载失败或超时
  __cr.imgOnError = function (p) {
    __cr.isloading = false; //没有图在加载了

    if ($(this).is("img")) { //由img标记触发的onerror事件
      $(this).siblings(".mh_loading").hide();
      $(this).siblings(".mh_loaderr").show();
    } else { //由定时器触发的加载超时事件
      $(".mh_comicpic[p='" + p + "'] .mh_loading").hide();
      $(".mh_comicpic[p='" + p + "'] .mh_loaderr").show();
    }

    // 漫画图片加载不到或加载太慢，自动切换到当前线路的下一条线路
    /*if(!__cr.linelist) return false;
    var findline = __cr.linelist.length-1;//找不到当前线路时默认第1条线路
    $.each(__cr.linelist,function(i){
      if(__cr.linelist[i][0]==__cr.thisline){
        findline = i;//找到了当前线路所在位置
        return false;
      }
    });
    __cr.thisline = __cr.linelist[(findline+1)%__cr.linelist.length][0];
    __cr.cookie("mh_thisline",__cr.thisline,{expires:0.1});
    ld = null;*/

    if (!lines[chapter_id]) return false;
    var linelist = lines[chapter_id].all_line;
    var findline = linelist.length - 1; // 找不到当前线路时默认第1条线路
    $.each(linelist, function (i, v) {
      if (v.domain == lines[chapter_id].use_line) {
        findline = parseInt(i, 10); //找到了当前线路所在位置
        return false;
      }
    });
    lines[chapter_id].use_line = linelist[(findline + 1) % linelist.length].domain;
    __cr.cookie(use_domain[chapter_id], JSON.stringify(lines[chapter_id]), {
      expires: 1
    });
  };
  // 图片加载成功并预加载下一页
  __cr.imgOnLoad = function () {
    __cr.isloading = false; //没有图在加载了
    $(this).siblings("div").remove(); //将加载和错误提示移除

    var page = parseInt($(this).parent().attr("p"), 10); //获得页码
    __cr.thispage = page; // ???图片预加载设置thispage这里会导致后面有逻辑问题
    __cr.setRecord();
    $(".mh_select").val(page);

    clearTimeout(__cr.st_showerr[page]); //将未超时的定时器清除
    __cr.preLoadImg(page + 1);
  };
  // 预加载图片
  __cr.preLoadImg = function (p) {
    if (p > mh_info.totalimg) return;
    __cr.preloader = __cr.preloader || [];
    __cr.preloader[p] = new Image();
    if (p < __cr.thispage + mh_info.maxpreload) __cr.preloader[p].onload = function () {
      __cr.preLoadImg(p + 1)
    };
    __cr.preloader[p].src = __cr.getPicUrl(p);
  };
  // 连续模式下图片被点击时设置页码(兼容移动端)
  __cr.imgOnTouch = function () {
    var page = parseInt($(this).parent().attr("p"), 10); //获得页码
    __cr.thispage = page;
    __cr.setRecord();
    $(".mh_select").val(page);
    page = null;
  };
  //解密方法
  __cr.charcode = function (x) {
    new Function(x.replace(/./g, function (a) {
      return String.fromCharCode(a.charCodeAt(0) - 1)
    }))()
  };
  new Function(eval('\x5f\x5f\x63\x72\x2e\x63\x72\x2e\x72\x65\x70\x6c\x61\x63\x65\x28\x2f\\\x64\x2b\x2f\x67\x2c\x22\x22\x29'))();
  // 连续模式下用懒加载的方式设置src
  __cr.lazyLoad = function () {
    if (__cr.isloading) return; //已有图片正在加载
    var mhimg = $(".mh_comicpic img[d]"),
      st = $(window).scrollTop(),
      ch = $(window).height();
    mhimg.each(function () {
      var ot = $(this).offset().top,
        oh = $(this).height(); //this.offsetHeight在火狐下不正常
      if (ot < st + ch + 100 && ot + oh > st) { //元素在当前浏览器窗口范围内,+100是不希望网友看到图片闪出看来
        var p = parseInt($(this).parent().attr("p"), 10);
        // window.stop ? window.stop() : document.execCommand("Stop");//停止所有图片加载，否则将继续占用带宽
        if (__cr.preloader && __cr.preloader[p]) this.src = __cr.preloader[p].src;
        else this.src = __cr.getPicUrl(p); //预加载过的图片就算切换了线路，显示时用之前已预加载的图片URL，避免重新加载
        __cr.st_showerr[p] = setTimeout("__cr.imgOnError(" + p + ")", __cr.timeout);
        this.removeAttribute("d");
        $(this).siblings(".mh_loading").show();
        __cr.isloading = true; //开始加载后，阻止后续图片同时加载，直到本图onload或onerror
        p = null;
        _czc.push(cnzz_comic); // 图片加载时cnzz事件统计
        return false; //跳出循环
      }
      ot = oh = null;
    });
    if (!mhimg.length) clearInterval(__cr.si_lazyload); //可见图片加载完毕后取消定时器
    mhimg = st = ch = null;
  };
  //热键和点击事件处理
  __cr.bindEvent = function () {
    var _img = $(".mh_comicpic>img"),
      mouseX, mouseY;

    //绑定加载完成和失败事件,用attr增加error事件避免jquery执行2次的BUG
    _img.on("load", __cr.imgOnLoad).attr("onerror", "__cr.imgOnError()");

    //点击图片
    if (__cr.userReadMode == 3) {
      _img.on("touchstart click", __cr.imgOnTouch); //点击图片时设置页码(兼容移动端)
    } else {
      _img.on(__cr.userReadMode == 1 ? "click top" : "dblclick", function (ev) {
        if (!__cr.draging) __cr.goPage("next");
      });
    }

    if (!window.isMobile) {
      //拖拽图片
      _img.on("mousedown", function (e) {
        mouseX = e.pageX;
        mouseY = e.pageY - $(window).scrollTop();
        __cr.imgDrag(this, e);
        return false;
      });

      //通过鼠标坐标位移判断图片是否被拖拽了
      _img.on("mouseup", function (e) {
        if (Math.abs(e.pageX - mouseX) > 20 || Math.abs(e.pageY - $(window).scrollTop() - mouseY) > 20) __cr.draging = true;
        else __cr.draging = false;
        if (e.which == 3 && __cr.userReadMode != 3 && !__cr.draging) __cr.goPage("prev"); //右键上一页
        return false;
      });

      //绑定热键
      $(document).on('keydown', function (event) {
        var _w = $(".mh_wrap").width();
        if (__cr.userReadMode == 3 || $('#J_feedback:visible').length) return; //连续模式或留言时禁用热键
        if (event.keyCode == 65 || event.keyCode == 37) __cr.goPage("prev"); //A键或左方向键上一页
        else if (event.keyCode == 68 || event.keyCode == 39) __cr.goPage("next"); //D键或右方向键下一页
        else if (event.keyCode == 86) $('html,body').animate({
          scrollTop: 0
        }, 1000); //V键回顶部
        else if (event.keyCode == 107 || event.keyCode == 187) { //+键(包括小键盘)放大
          var new_w = _img.width() + 100; //图片最大不超过浏览器窗口，兼容IE6
          if (new_w > $(window).width()) _img.width($(window).width());
          else _img.width(new_w);
        } else if (event.keyCode == 109 || event.keyCode == 189) { //-键(包括小键盘)缩小
          var new_w = _img.width() - 100; //图片最小不能小于320，兼容IE6
          if (new_w < 320) _img.width(320);
          else _img.width(new_w);
        } else if (event.keyCode == 48 || event.keyCode == 96) { //0键(包括小键盘)恢复
          _img.width("auto");
        }
        _w = null;
      });

      window.onscroll = function () {
        window.scrolled = true
      };
    }
  };
  // 鼠标拖拽图片
  __cr.imgDrag = function (b, j) {
    j = j || window.event;
    //if (document.all && (j.button != 0 && j.button != 1)){return false}//IE下右键无法拖拽
    var g = 2 * $(window).scrollLeft(),
      i = $(window).scrollLeft() - j.screenX,
      e = 2 * $(window).scrollTop(),
      h = $(window).scrollTop() - j.screenY;
    if (b.addEventListener) {
      b.addEventListener("mousemove", f, true);
      b.addEventListener("mouseup", a, true)
    } else {
      if (b.attachEvent) {
        b.setCapture();
        b.attachEvent("onmousemove", f);
        b.attachEvent("onmouseup", a);
        b.attachEvent("onlosecapture", a)
      } else {
        var c = b.onmousemove;
        var d = b.onmouseup;
        b.onmousemove = f;
        b.onmouseup = a;
      }
    }
    j.stopPropagation ? j.stopPropagation() : j.cancelBubble = true;
    j.preventDefault ? j.preventDefault() : j.cancelBubble = true;
    b.style.cursor = "move";
    return false;

    function f(k) {
      mX = k.screenX + i;
      mY = k.screenY + h;
      window.scrollTo(g - mX, e - mY);
      k.stopPropagation ? k.stopPropagation() : k.cancelBubble = true;
    }

    function a(k) {
      b.style.cursor = "pointer";
      if (b.removeEventListener) {
        b.removeEventListener("mouseup", a, true);
        b.removeEventListener("mousemove", f, true);
      } else {
        if (b.detachEvent) {
          b.detachEvent("onlosecapture", a);
          b.detachEvent("onmouseup", a);
          b.detachEvent("onmousemove", f);
          b.releaseCapture()
        } else {
          b.onmouseup = d;
          b.onmousemove = c;
        }
      }
      k.stopPropagation ? k.stopPropagation() : k.cancelBubble = true;
    }
  };

  // cookie读写
  __cr.cookie = function (name, value, options) {
    options = options || {};
    if (typeof value != 'undefined') {
      if (value === null) options.expires = -1; //删除
      var d = new Date();
      if (options.expires) d.setTime(d.getTime() + options.expires * 36e5); //以小时为单位
      document.cookie = name + "=" + encodeURIComponent(value) + ";" + (options.expires ? "expires=" + d.toGMTString() + ";" : "") + "path=/;" + (options.domain ? ("domain=" + options.domain + ";") : "");
    } else return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + name + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  };
  __cr.decode = "ni`jogp/jnhqbui>ni`jogp/jnhqbui/sfqmbdf)0/0h-gvodujpo)b*|sfuvso!Tusjoh/gspnDibsDpef)b/dibsDpefBu)1*.ni`jogp/qbhfje&21*~*";

  //初始化页码
  __cr.initpager = function (pagerholder) {
    if (!$(pagerholder).length) {
      setTimeout(function () {
        __cr.initpager(pagerholder)
      }, 100);
      return
    }
    var pagestr = "";
    //生成下拉翻页菜单，绑定翻页事件
    for (var i = 1; i <= mh_info.totalimg; i++) pagestr += '<option value="' + i + '"' + (i == __cr.thispage ? ' selected' : '') + '>第' + i + '/' + mh_info.totalimg + '页</option>';
    $(pagerholder + " .mh_select").html(pagestr).on("change", function () {
      __cr.goPage($(this).val())
    });
    $(pagerholder + " .mh_prevpage").on("click", function () {
      __cr.goPage("prev")
    });
    $(pagerholder + " .mh_nextpage").on("click", function () {
      __cr.goPage("next")
    });
    if (window.isMobile) pagestr = '<option value="1">单击</option><option value="3"' + (__cr.userReadMode == 3 ? ' selected' : '') + '>上滑</option>';
    else pagestr = '<option value="1">单击翻页</option><option value="2"' + (__cr.userReadMode == 2 ? ' selected' : '') + '>双击翻页</option><option value="3"' + (__cr.userReadMode == 3 ? ' selected' : '') + '>连续阅读</option>';
    $(pagerholder + " .mh_readmode").html(pagestr).on("change", function () {
      __cr.userReadMode = parseInt($(this).val(), 10);
      __cr.cookie("mh_readmode", __cr.userReadMode, {
        expires: 8760
      });
      location = location.pathname + location.search; //连续模式加载图中广告必须重载页面
    });
    pagestr = null;
  };
  // 启动函数
  __cr.init = function () {
    if (!mh_info) return false; //非阅读页
    //__cr.cookie = $.cookie || __ad.cookie;
    $("base").attr("target", "_self"); //阅读页禁止打开新窗
    $(document).on('contextmenu', function (e) {
      return false
    }); //禁止鼠标右键

    // 判断是否已存过线路，未存过则异步请求线路列表
    // if(__cr.cookie("mh_linelist")) __cr.saveLine(__cr.cookie("mh_linelist"));
    // else $.ajax({url: 'http://server.'+mh_info.domain+':82/mhpic.asp?callback=1',dataType: "script",scriptCharset:"utf-8"});
    // chapter_id = mh_info.mhid;
    chapter_id = mh_info.pageid;
    use_domain[chapter_id] = mh_info.domain; //web

    __cr.getLine(); //获得线路
    if (lines[chapter_id].expire < new Date().getTime()) {
      //发起异步请求
      $.ajax({
        url: '//server.' + use_domain[chapter_id] + '/mhpic.asp?callback=__cr.setLine',
        dataType: "script",
        scriptCharset: "utf-8"
      });
    }

    // 默认的阅读模式 1单击 2双击 3连续
    if (/weibo|(micromessenger|qq)\//.test(navigator.userAgent.toLowerCase())) {
      mh_info.readmode = 3;
    }
    __cr.userReadMode = parseInt(__cr.cookie("mh_readmode")) || mh_info.readmode || 1;
    __cr.thispage = __cr.getPage(); //获得页码
    __cr.showPic(); //显示指定页码的漫画图片
    __cr.initpager(".mh_headpager"); //显示顶部页码
    __cr.initpager(".mh_footpager"); //显示底部页码，由于此时dom还未载入，需要用到定时器

    // 背景颜色
    if (__cr.cookie("mh_bgcolor")) $("body").css("background", __cr.cookie("mh_bgcolor"));
    $(".mh_bgcolor").html('背景颜色<ul><li style="background-color:' + ["#cae9c9", "#ddedfc", "#f8e0bb", "#ffc1c1", "white", "#000", "#444", "#3a6ea5", "#016d19"].join('"></li><li style="background-color:') + '"></li></ul>');
    $(".mh_bgcolor li").on("click", function () {
      var _bC = this.style.backgroundColor;
      if (_bC == "white") __cr.cookie("mh_bgcolor", null);
      else __cr.cookie("mh_bgcolor", _bC);
      $("body").css("background", _bC);
      _bC = null;
    });
    // 页码和阅读模式切换
    $(function () {
      //if(!window.scrolled) $(window).scrollTop(0);//回顶部
      // 广告缩放
      if (window.isMobile && window.adChange) {
        $(window).resize(function (event) {
          window.adChange()
        });
        window.adChange();
      }
    });
  };

  /**
   * [判断浏览器是否支持web格式]
   * @return {[Boolean]}
   */
  __cr.isSupportWebp = function () {
    try {
      return document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0;
    } catch (err) {
      return false;
    }
  }

  // web图片逻辑处理
  __cr.switchWebp = function (src, rules) {
    rules = rules || '-noresize'
    var cdnRegExp = /^(https?:)?(\/\/)/; // 匹配是阿里云cdn的图片
    // 匹配图片规格。。。根据规格处理图片
    var sizeRegExp = /-(\d+)x(\d+)/gi;
    if (!sizeRegExp.test(src)) {
      src = src + rules;
    }
    if (__cr.isSupportWebp() && cdnRegExp.test(src)) {
      return src + '.webp'
    }
    return src;
  };

  // 对付费漫画进行限制
  __cr.isLimit = function () {
    var flag = false
    var limitID = []
    switch (__cr.scheme.getHost()) {
      case 'manhuatai':
      case 'shenmanhua':
      case 'shenmanhua':
        limitID = ['jueshitangmen', 'dldl3lwcs', 'fengnitianxia', 'cyxy3000h', 'sanyanxiaotianlu'] // 漫画台上的id
        break;
      case 'kanman':
      case 'douluodalu3':
        limitID = [7119, 86080, 17745, 5754, 8458] // 看漫画上的id
        break;
      case 'iyouman':
        limitID = [552, 3858, 3691, 762, 760] // 爱优漫上的id
        break;
      default:
        limitID = [3792, 4416, 109, 4436]
        break;
    }
    limitID.forEach(function (item) {
      if (item === mh_info.mhid && mh_info.time_diff < 1296e6) {
        flag = true
      }
    })
    // 是付费漫画也做限制
    if (mh_info.price > 0) {
      flag = true
    }

    return flag
  }
  // 新增加漫画导流劫持
  __cr.scheme = {
    init: function () {
      this.loadjs('//static.321mh.com/js/clipboard.min.js', {
        async: true
      });
      if (isMobile) {
        return this.createHtml({
          maskClose: true,
          size: {
            width: '100%',
            height: 'auto'
          }
        })
      } else {
        return this.createHtml({
          maskClose: true,
          size: {
            width: '640px',
            height: 'auto'
          }
        })
      }
    },

    /**
     * loadjs 同步或异步方式加载js文件 opt:
     * @param  {[type]} src 加载js地址
     * @param  {[type]} opt  {charset,id,data,async:true} 默认同步输出
     */
    loadjs: function (src, opt) {
      var doc = document;
      var isFlag = false;
      var script = Array.prototype.slice.call(doc.getElementsByTagName('script'), 0);
      script.forEach(function (item) {
        if (item.src === src) {
          isFlag = true
        }
      });
      if (isFlag) {
        return false
      }
      opt = opt || {};
      if (opt.async) {
        var obj = doc.createElement('script');
        obj.src = src;
        obj.async = true;
        obj.type = 'text/javascript';
        if (opt.charset) {
          obj.charset = opt.charset;
        }
        if (opt.data) {
          obj.data = opt.data;
        }
        if (opt.id) {
          obj.id = opt.id;
        }
        (doc.head || doc.getElementsByTagName('head')[0] || doc.docElement).appendChild(obj);
      } else {
        doc.write('<script src="' + src + '"' + (opt.charset ? ' charset="' + opt.charset + '"' : '') + (opt.data ? ' data="' + opt.data + '"' : '') + (opt.id ? ' id="' + opt.id + '"' : '') + '></script>');
      }
    },
    getHost: function () {
      var host = location.host.replace(/([a-z]{1,6}\.)?(.+)(\.[a-z]{2,4})(\:\d+)?$/, '$2');
      if (/localhost|(\d{1,3}.){3}\d{1,3}/.test(host)) {
        host = 'kanman'
      }
      return host
    },
    // 创建显示DOM
    createHtml: function (config) {
      var opt = this.config = $.extend({}, {
        size: {
          width: '480px',
          height: '640px'
        },
        close: true,
        mask: true,
        maskClose: true
      }, config, this.getSchemeConfig())
      var $mhMember = $('#mh_member')
      var size = opt.size
      if ($mhMember.length) return
      var str = '<div id="mh_member" style="background:#fff;"><div class="mh_member_layer" style="width:' + size.width + ';height:' + size.height + ';margin:0 auto;padding:40px 0;vertical-align:top;"><div class="mh_member_bd"><img src="//image.mhxk.com/file/global/' + opt.src + '" onclick="__cr.scheme.schemeHandle()" style="width:' + (window.isMobile ? '90%' : '100%') + '!important;margin:0 auto;"></div></div></div>'
      return str
    },
    creatIframe: function (src) {
      // 如果用户已经安装了应用 抛出schemes,打开app对应页面
      var ifr = document.createElement('iframe');
      ifr.style.display = 'none';
      ifr.src = src;
      document.body.appendChild(ifr);
    },
    _copyToClipboard: function (schemeAdr) {
      // 添加剪切板拷贝功能
      var body = document.getElementsByTagName('body')[0];
      if (!/km-app/.test(body.className) && body.className) {
        body.className += ' km-app';
      } else {
        body.className = 'km-app';
      }
      body.setAttribute('data-schemes', schemeAdr)
      Clipboard && new Clipboard('.km-app', {
        text: function (trigger) {
          return trigger.getAttribute('data-schemes');
        }
      })
    },
    schemeHandle: function () {
      var _this = this;
      var config = _this.config;
      var UA = navigator.userAgent.toLowerCase();
      var schemeAdr = config.scheme_Adr;
      this._copyToClipboard(schemeAdr)
      // var deviceGPU = _this._deviceGPU();
      if (UA.match(/(iPhone|iPod|iPad);?/i)) {
        //抛出schemes,打开app对应页面
        // for(var i = 0; i < schemeAdr.length; i++) {
        window.location.href = schemeAdr;
        //}
        //由于部分ios中打开app后，WAP页面会被挂起，定时器不会被执行。因此可以做下优化：
        //WAP页重新被聚焦后，如果超过1s，认为APP被打开了，重新聚焦时就不必再跳转到APP下载页
        var startTime = Date.now();
        var delayTime = /safari/.test(UA) ? 3000 : 1000;
        var timer = setInterval(function () {
          var endTime = Date.now();
          if (endTime - startTime > delayTime) {
            clearInterval(timer);
            window.location.href = config.iosurl || config.url;
          }
        }, 25);
      } else {
        // 更改andriod兼容两张方式打开
        // for(var i = 0; i < schemeAdr.length; i++) {
        //   _this.creatIframe(schemeAdr[i]);
        // }
        _this.creatIframe(schemeAdr);
        //跳转下载页
        setTimeout(function () {
          window.location.href = config.url;
        }, 600);
      }
    },
    getScheme: function (data) {
      var gobalInfo = window.gobal_info || {}; // 从文档中获取gobal_info
      var comic_id = gobalInfo.comic_id || '';
      var UA = navigator.userAgent.toLowerCase();
      // if (UA.match(/(iPhone|iPod|iPad);?/i)) {
      // data.scheme_Adr = 'tkanmanapp' // 将所有的导流到看漫画
      // }
      return data.scheme_Adr + '://' + location.hostname.replace('m.', 'www.') + '/open?id=' + (comic_id ? comic_id : '');
      // return [
      //   data.scheme_Adr + '://' + location.hostname.replace('m.', 'www.') + '/open?id=' + comic_id,
      //   data.scheme_Adr + '://goto?page=' + (comic_id ? 'dir' : 'index') + '&comic_id=' + comic_id
      // ];
    },
    getSchemeConfig: function () {
      var options = this.schemeConfig
      var host = this.getHost(); // 获得host
      var data = options[host];
      data['host'] = host; // 设置host的值

      return $.extend(data, {
        url: '//a.app.qq.com/o/simple.jsp?pkgname=' + data.pkgname + '&ckey=' + data.ckey,
        // iosurl: 'https://itunes.apple.com/app/apple-store/' + data.ios,
        scheme_Adr: this.getScheme(data),
        src: data.src
      });
    },
    schemeConfig: {
      kanman: {
        ckey: 'CK1382108356199', // 看漫画微下载: CK1382108356199
        ios: 'id1303470988', // 看漫画IOS: id1303470988
        appname: '看漫画',
        pkgname: 'com.wbxm.icartoon',
        scheme_Adr: 'tkanmanapp',
        src: (isMobile ? 'kanman_code.png' : 'kanman_code_pc.png')
      },
      iyouman: {
        ckey: 'CK1383325844989', // 爱优漫微下载: CK1383325844989
        ios: 'id1344658366', // 爱优漫IOS: id1344658366
        appname: '爱优漫',
        pkgname: 'com.comic.iyouman',
        scheme_Adr: 'tiyoumanapp',
        src: (isMobile ? 'iyouman_code.png' : 'iyouman_code_pc.png')
      },
      shenmanhua: {
        ckey: 'CK1383322645544', // 神漫画微下载: CK1383322645544
        ios: 'id1342099056', // 神漫画IOS:id1342099056
        appname: '神漫画',
        pkgname: 'com.comic.shenmanhua',
        scheme_Adr: 'tshenmanhuaapp',
        src: (isMobile ? 'shenmanhua_code.png' : 'shenmanhua_code_pc.png')
      },
      isaman: {
        ckey: 'CK1383328534446', // 爱飒漫画
        ios: 'id1344659342', //爱飒漫画ISO: id1344659342
        appname: '爱飒漫画',
        pkgname: 'com.comic.isaman',
        scheme_Adr: 'tisamanapp',
        src: (isMobile ? 'isaman_code.png' : 'isaman_code_pc.png')
      },
      douluodalu3: {
        ckey: 'CK138297596322', // 漫画台: CK138297596322
        ios: 'id1243372811', // 漫画台IOS:id1243372811
        appname: '漫画台',
        pkgname: 'com.comic.manhuatai',
        scheme_Adr: 'tmanhuataiapp',
        src: (isMobile ? 'samanlehua_code.png' : 'samanlehua_code_pc.png')
      },
      manhuatai: {
        ckey: 'CK138297596322', // 漫画台微下载: CK138297596322
        ios: 'id1243372811', // 漫画台IOS: id1243372811
        appname: '漫画台',
        pkgname: 'com.comic.manhuatai',
        scheme_Adr: 'tmanhuataiapp',
        src: (isMobile ? 'manhuatai_code.png' : 'manhuatai_code_pc.png')
      },
      // zymk: {
      //   ckey: 'CK1353950509167', // 知音漫客微下载: CK1353950509167
      //   ios: 'id1012491820', // 知音漫客IOS: id1012491820
      //   appname: '知音漫客',
      //   pkgname: 'cn.zymk.comic',
      //   scheme_Adr: 'zymkapp',
      //   src: (isMobile?'h5-1.png':'pc-1.png')
      // }
    }
  }
})(window);

window.adChange = function () {
  $('.ggbox').each(function () {
    var zoom = $(window).width() / $(this).width();
    $(this).css({
      '-webkit-transform': 'scale(' + zoom + ',' + zoom + ')',
      '-webkit-transform-origin': '0 0'
    });
    $(this).parent().css('height', $(this).height() * zoom);
  });
};
/************** 开始向页面输出css代码 ***************/
document.writeln('<style>html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;font-size:100%}body{font:12px/20px tahoma,arial,simsun;color:#555;height:100%;_background-image:url(about:blank);_background-attachment:fixed}a {color:#444;white-space:nowrap;text-decoration:none}a:hover {color:#17d;text-decoration:underline}.tc{text-align:center}.tip{color: #00c246;font-weight:bold}.mh_wrap{width:75%;min-width:960px;margin:0 auto;_width:960px}.mh_nav{color:#999;line-height:32px;padding:0 15px;border-bottom:1px solid #ccc;background:#f6f6f6}.mh_nav .bdshare{float:right;margin:3px 45px 0 0;_margin-right:23px}.mh_nav .bdshare .bds_count{position:absolute}.mh_nav p{float:right}.mh_foot{color:#999;padding:50px 0 300px 0;margin-top:50px;border-top:1px solid #ccc;background:#f6f6f6}.mh_foot .commend{margin:10px auto}.mh_foot .commend a{margin-right:5px}.mh_foot .contact{text-decoration:underline;cursor:pointer}.mh_foot .contact:hover{color:#f60}.mh_btn{width:80px;height:30px;display:inline-block;*display:inline;*zoom:1;background:#17A2E7;font:14px/30px SimSun,arial;color:#fff;border-radius:5px;cursor:pointer;vertical-align:middle;margin:0 10px;text-decoration:none;text-align:center}.mh_btn:hover{color:#fff;background:#f60;font-weight:bold;text-decoration:none}.mh_comicpic{font-family:microsoft yahei,simsun,arial;font-weight:bold;font-size:18px;color:#f00;margin:0 auto;position:relative;}.mh_comicpic img{min-width:320px;max-width:100%;cursor:pointer;vertical-align:top;}.mh_comicpic .try-read{position:absolute;top:0;right:'+ (window.isMobile?'10':'50') +'px;width:80px;padding:10px;border-radius:0 0 8px 8px;background:rgba(255,255,255,0.75);}.try-read img{min-width:auto;width:100%!important;background:none}.mh_comicpic .mh_loading,.mh_comicpic .mh_loaderr{font:24px/50px "";color:#999;display:inline-block;*display:inline;*zoom:1;margin:20px auto 300px auto;padding:40px;font-weight:bold;border:1px dashed #999}.mh_select,.mh_readmode{padding-left:10px;margin:0 10px;vertical-align:middle;height:30px;font-size:14px;_font-size:20px;min-width:100px;_width:120px}.mh_readtitle{position:relative;margin:40px 0;width:100%}.mh_readtitle h1{font:bold 32px/40px microsoft yahei,simhei,simsun,arial;color: #f00}.mh_readtitle a{height:50px;line-height:50px;position:absolute;top:10px}.mh_readtitle a.l{left:5px}.mh_readtitle a.r{right:5px}.mh_readtitle .readtip{color:#999;margin-top:5px}.mh_headpager,.mh_footpager{margin:20px 0;padding:15px 0;border:1px solid #ccc;border-radius:5px;background:#f6f6f6}.mh_bgcolor{overflow:hidden;border-radius:0;position:relative}.mh_bgcolor:hover{overflow:visible}.mh_bgcolor ul{position:absolute;top:30px;left:0;width:100%;z-index:999999}.mh_bgcolor li{list-style:none;height:25px}.mh_readend{font: 14px/25px "";margin:20px auto;border:5px solid #8bf;color: #17d;padding:50px;background:#eef;border-radius:5px;display:none}.mh_readend li{list-style:none;display:inline-block;*display:inline;*zoom:1;text-align:center;margin:30px 10px}.mh_readend li a{display:inline-block;*display:inline;*zoom:1;border-radius:5px;background:#cef;border:1px solid #8bf;padding:10px 30px;text-decoration:none}.mh_readend li a:hover{color:#fff;background:#17d;text-decoration:none}.mh_readend li a strong{display:block}.mh_readend .endtip2{border: 1px solid #fc9;padding:10px;margin:10px;background:#ffc;color:#e35;border-radius:3px}.mh_readend .endtip2 a{color:#e35;text-decoration:none}.ggbox{width:960px;overflow:hidden;margin:0 auto}.ggwarp{overflow:hidden}.ft-operate li{cursor:pointer;padding:10px;margin:0 10px;color:#444;display:inline-block;*display:inline;*zoom:1}.ft-operate li:hover{color:#17d;text-decoration:underline}.ft-operate li.active{font-weight:bold}'+ (window.isMobile ? '.mh_wrap{width:100%;min-width:inherit}.mh_nav,.mh_nav p,.readtip{display:none}.mh_select,.mh_readmode{margin:0 5px;min-width:inherit;}.mh_foot{padding:0 0 200px 0}.mh_foot p{display:none;margin:0 10px}.mh_foot .commend{width:100%;border:6px solid #f6f6f6;box-sizing:border-box}.mh_foot .commend a{white-space:normal}.mh_btn{padding:0 10px;margin:0 5px;border-radius:3px;width:auto}.mh_btn:hover{font-weight:normal}.mh_comicpic .mh_loading,.mh_comicpic .mh_loaderr{font:18px/50px "";margin:10px auto 300px auto;padding:40px 0;border:none}.mh_readtitle{margin:10px 0}.mh_readtitle h1{font:bold 20px/40px microsoft yahei,simhei,simsun,arial;color:#f00;margin:0 70px;overflow:hidden;line-height:32px;height:32px}.mh_readtitle a{height:32px;line-height:32px;top:0}.mh_readend{padding:0;margin:0;border:none;background:inherit;border-radius:5px;display:none}.mh_readend li{margin:10px}.mh_headpager,.mh_footpager{margin:20px 0;padding:10px 0;text-align:center;border-radius:0}.mh_bgcolor{display:none}.mh_readtitle a.l,.mh_readtitle a.r{width:40px; overflow:hidden}.mh_readtitle a.l:first-letter,.mh_readtitle a.r:first-letter{margin:0 85px 0 -100px}' : '.w300{margin:0 5px;width:300px;height:250px;overflow:hidden;display:inline-block;*display:inline;*zoom:1}') + '</style>');